package com.wanwan.websocket.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wanwan.websocket.entity.MessageInfo;
import com.wanwan.websocket.entity.StatusInfo;
import com.wanwan.websocket.entity.UserInfo;
import com.wanwan.websocket.redis.RedisUtils;
import com.wanwan.websocket.server.WebSocketServer;
import com.wanwan.websocket.service.MessageInfoService;
import com.wanwan.websocket.service.StatusInfoService;
import com.wanwan.websocket.service.UserInfoService;
import entity.ResultBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.Date;
import java.util.List;
@Slf4j
@Controller
@RequestMapping("/haha")
public class WebSocketController {

    @Autowired
    private MessageInfoService messageInfoService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private StatusInfoService statusInfoService;

    @Autowired
    private RedisUtils redisUtils;

    @RequestMapping("/index")
    public ModelAndView index() {
        ModelAndView modelAndView = new ModelAndView("index");
        return modelAndView;
    }

    @RequestMapping("/toadd")
    public ModelAndView add() {
        ModelAndView modelAndView = new ModelAndView("add");
        List<UserInfo> userInfos = userInfoService.list();
        modelAndView.addObject("list",userInfos);
        return modelAndView;
    }

    @GetMapping("/getmessage")
    @ResponseBody
    public ResultBean getMessage(String userId){
        //用户id redis获取用户消息
        String statusInfos = "";
        if (redisUtils.get(userId) != null){
            statusInfos = redisUtils.get(userId).toString();
            return new ResultBean(200,"访问成功",statusInfos);
        }else {
            //查询数据库
            QueryWrapper<StatusInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id",userId);
            queryWrapper.eq("status",0);
            List<StatusInfo> statusInfoList = statusInfoService.list(queryWrapper);
            if (CollectionUtils.isEmpty(statusInfoList)) {
                return new ResultBean(200,"没有未读消息");
            }else {
                redisUtils.set(userId,JSON.toJSONString(statusInfoList));
                return new ResultBean(200,"访问成功",statusInfoList);
            }
        }
    }

    @RequestMapping("/add")
    @ResponseBody
    public ResultBean add(String title,String content,String[] userIds) throws IOException {
        //todo 时间转换
        MessageInfo messageInfo = new MessageInfo();
        messageInfo.setContent(content);
        messageInfo.setContent("无论走到哪，都要记住过去都是假的，" +
                "回忆是一条没有归途的路，以往的一切春天都无法复原，" +
                "即使最狂热最坚贞的爱情，归根结底也不过是一种瞬息即逝的现实，" +
                "唯有孤独永恒。");
        messageInfo.setSendTime(new Date());
        messageInfo.setTitle(title);
        boolean i = messageInfoService.save(messageInfo);
        if (i){
            for (String userId : userIds){
                StatusInfo statusInfo = new StatusInfo();
                statusInfo.setUserId(Integer.parseInt(userId));
                statusInfo.setTitleMessage(messageInfo.getTitle());
                statusInfo.setStatus(0);
                statusInfo.setMessageId(messageInfo.getId());
                statusInfo.setSendTime(new Date());
                statusInfoService.save(statusInfo);
            }
        }else {
            log.error("消息添加失败");
        }
        //推送消息
        for (String userId : userIds){
            QueryWrapper<StatusInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id",userId);
            queryWrapper.eq("status",0);
            List<StatusInfo> statusInfos = statusInfoService.list(queryWrapper);
            //连接进了websocket
            redisUtils.set(userId,JSON.toJSONString(statusInfos));
            WebSocketServer.sendInfo(JSON.toJSONString(statusInfos),userId);
        }
        return new ResultBean(200,"消息发送成功");
    }

    @RequestMapping("/index/test")
    @ResponseBody
    public ResultBean test() {
        //ModelAndView modelAndView = new ModelAndView("index");
        return new ResultBean("测试");
    }

}
